<template>
  <div>
    登陆页面
    <van-form>
      <van-field
        v-model="user.mobile"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="user.code"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      >
        <template #button>
          <van-button size="small" disabled v-if="isSend == true">
            <van-count-down :time="1000 * 10" format="sss" @finish="isSend = false"></van-count-down>
          </van-button>
          <van-button size="small" type="primary" v-else @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" @click="dl">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isSend: false,
      user: {
        mobile: "",
        code: ""
      }
    };
  },
  methods: {
    dl() {
      var phone_pertten = /^1[34578]\d{9}$/;
      var code_pertten = /^\d{6}$/;
      //判断手机号或者验证码是否为空
      if (this.user.mobile == "" || this.user.code == "") {
        this.$toast.fail("手机号或者验证码不能为空");
        return false;
      }
      //手机格式校验失败的时候
      if (!phone_pertten.test(this.user.mobile)) {
        this.$toast.fail("手机格式不正确");
        return false;
      }
      //验证码格式错误
      if (!code_pertten.test(this.user.code)) {
        this.$toast.fail("验证码格式不正确");
        return false;
      }
      if (this.user.mobile == "" || this.user.code == "") {
        this.$toast.fail("请输入内容");
        return false;
      } else {
        this.$axios
          .post("/authorizations", this.user)
          .then(res => {
            console.log(res);

            //把用户登陆的基本信息存储到vuex中
            this.$store.commit("login", res.data);

            //提示登陆成功
            this.$toast.success("登陆成功");
            //跳转到首页
            let url = this.$route.query.redirect || "/my";
            this.$router.replace(url);
          })
          .catch(error => {
            console.log(error.response.data.message);
            this.$toast.fail("请求登陆接口的信息失败");
          });
      }
    },
    sendCode() {
      //修改发送状态
      this.isSend = true;
      //请求发送验证码的接口信息
    }
  }
};
</script>

<style lang="scss" scoped>
</style>